package com.timber.util;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

import com.borland.jbcl.layout.VerticalFlowLayout;


public class SearchableComboDialog extends SearchableDialog {
	public SearchableComboDialog(JFrame parent, SearchableComboBox pSearchableComboBox, boolean mSelect) {
		super(parent, true);
		try {
			searchableComboBox = pSearchableComboBox;
			this.multiSelect = mSelect;
			jbInit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SearchableComboDialog(JDialog parent, SearchableComboBox pSearchableComboBox, boolean mSelect) {
		super(parent, true);
		try {
			searchableComboBox = pSearchableComboBox;
			this.multiSelect = mSelect;
			jbInit();
		} catch (Exception e) {
			Util.error("SearchableComboDialog", e);
		}
	}

	protected JPanel pCenter = new JPanel();
	protected JPanel pSouth = new JPanel();
	protected JLabel jLabel1 = new JLabel();
	protected JLabel jLabel2 = new JLabel();
	protected JButton btnSelect = new JButton();
	protected JButton btnDeselect = new JButton();
	protected GridBagLayout gridBagLayout1 = new GridBagLayout();
	protected JPanel pButtons = new JPanel();
	protected VerticalFlowLayout verticalFlowLayout1 = new VerticalFlowLayout();
	protected JButton btnClose = new JButton();
	protected JButton btnOk = new JButton();
	protected JButton btnClear = new JButton();
	protected SearchableComboBox searchableComboBox;
	protected boolean multiSelect = false;
	// protected JComboBox selectionCoB = new JComboBox();
	protected BorderLayout borderLayout1 = new BorderLayout();
	// protected SearchableComboSelectionDialog selectionDialog = new SearchableComboSelectionDialog(this);
	protected JButton btnDelete_ = new JButton();
	// protected JPanel jPanel1 = new JPanel();

	protected FlowLayout flowLayout2 = new FlowLayout();
	protected JPanel pToolBar = new JPanel();
	protected SLImageButton btnSave = new SLImageButton("Save");
	protected SLImageButton btnDelete = new SLImageButton("Delete");
	protected FlowLayout flowLayout3 = new FlowLayout();
	protected FlowLayout flowLayout1 = new FlowLayout();

	private void jbInit() throws Exception {
		setSize(710, 350);

		allItemsTable = new SLTableView(new SearchableComboTableModel(0));
		selectedItemsTable = new SLTableView(new SearchableComboTableModel(0));
		allTm = (SLTableModel) allItemsTable.getModel();
		selectedTm = (SLTableModel) selectedItemsTable.getModel();
		searchableControl = new SearchableControl(allItemsTable);

		this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		this.setTitle("Items Lookup");
		if (multiSelect)
			allItemsTable.getTable().getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		else
			allItemsTable.getTable().getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		selectedItemsTable.getTable().getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		pParent = (JPanel) this.getContentPane();
		pParent.setLayout(borderLayout1);
		jLabel1.setText("All Items");
		jLabel2.setText("Selected Items");
		allTm.addTableModelListener(new TableModelListener() {
			public void tableChanged(TableModelEvent e) {
				jLabel1.setText("All Items:   " + allTm.getRowCount());
			}
		});
		selectedTm.addTableModelListener(new TableModelListener() {
			public void tableChanged(TableModelEvent e) {
				jLabel2.setText("Selected Items:   " + selectedTm.getRowCount());
			}
		});

		btnSave.setToolTipText("Save Selection");
		btnSave.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				btnSave_actionPerformed(e);
			}
		});
		btnDelete.setToolTipText("Delete Selection");
		btnDelete.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				btnDelete_actionPerformed(e);
			}
		});

		btnSave.setImageAt(ImageMgr.getIcon(ImageMgr.SAVE24_ICON).getImage(), 0);
		btnSave.setPreferredSize(new Dimension(60, 45));
		// btnSave.setMinimumSize(new Dimension(25, 25));
		// btnSave.setMaximumSize(new Dimension(60, 50));
		btnSave.setThreeButtonStates(true);
		btnSave.setBackground(null);
		btnSave.setFocusRect(false);
		// btnSave.setLAF( false );
		btnSave.setOpaque(false);
		// btnSave.setForeground(Color.black);

		btnDelete.setImageAt(ImageMgr.getIcon(ImageMgr.CUT_ICON).getImage(), 0);
		btnDelete.setPreferredSize(new Dimension(60, 45));
		// btnDelete.setMinimumSize(new Dimension(25, 25));
		// btnDelete.setMaximumSize(new Dimension(60, 50));
		btnDelete.setThreeButtonStates(true);
		btnDelete.setBackground(null);
		btnDelete.setFocusRect(false);
		// btnDelete.setLAF( false );
		btnDelete.setOpaque(false);
		// btnDelete.setForeground(Color.black);

		// btnSelect.setFont(new java.awt.Font("Dialog", 1, 13));
		btnSelect.setPreferredSize(new Dimension(51, 21));
		btnSelect.setText("=>");
		btnSelect.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				btnSelect_actionPerformed(e);
			}
		});
		// btnDeselect.setFont(new java.awt.Font("Dialog", 1, 13));
		btnDeselect.setPreferredSize(new Dimension(51, 21));
		btnDeselect.setText("<=");
		btnDeselect.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				btnDeselect_actionPerformed(e);
			}
		});
		pCenter.setLayout(gridBagLayout1);
		pButtons.setLayout(verticalFlowLayout1);
		selectedItemsTable.setPreferredSize(new Dimension(250, 200));
		// btnClose.setFont(new java.awt.Font("Dialog", 1, 11));
		btnClose.setPreferredSize(new Dimension(72, 27));
		btnClose.setText("Cancel");
		btnClose.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				btnClose_actionPerformed(e);
			}
		});
		// btnOk.setFont(new java.awt.Font("Dialog", 1, 11));
		btnOk.setPreferredSize(new Dimension(49, 27));
		btnOk.setText("Ok");
		btnOk.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				btnOk_actionPerformed(e);
			}
		});
		// btnClear.setFont(new java.awt.Font("Dialog", 1, 11));
		// btnClear.setMinimumSize(new Dimension(60, 27));
		btnClear.setPreferredSize(new Dimension(63, 27));
		btnClear.setText("Clear");
		btnClear.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				btnClear_actionPerformed(e);
			}
		});
		pSouth.setLayout(flowLayout1);
		pButtons.setPreferredSize(new Dimension(60, 57));
		// pCenter.setMinimumSize(new Dimension(670, 90));
		pCenter.setPreferredSize(new Dimension(670, 217));

		// pParent.setMinimumSize(new Dimension(670, 254));
		// pParent.setPreferredSize(new Dimension(590, 300));

		pSouth.setPreferredSize(new Dimension(249, 35));
		pToolBar.setLayout(flowLayout3);
		flowLayout3.setAlignment(FlowLayout.LEFT);
		flowLayout3.setVgap(4);
		searchableControl.setPreferredSize(new Dimension(200, 23));
		allItemsTable.setPreferredSize(new Dimension(250, 200));
		pParent.add(pCenter, BorderLayout.CENTER);

		pCenter.add(searchableControl, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));

		pCenter.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
		pCenter.add(jLabel2, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
		pParent.add(pSouth, BorderLayout.SOUTH);

		pSouth.add(btnOk, null);
		pSouth.add(btnClear, null);
		pSouth.add(btnClose, null);
		pParent.add(pToolBar, BorderLayout.NORTH);
		pCenter.add(selectedItemsTable, new GridBagConstraints(2, 2, GridBagConstraints.REMAINDER, GridBagConstraints.REMAINDER, 0.1, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
		pCenter.add(pButtons, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
		pButtons.add(btnSelect, null);
		pButtons.add(btnDeselect, null);
		pCenter.add(selectionCoB, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
		pCenter.add(allItemsTable, new GridBagConstraints(0, 2, 1, 1, 0.2, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));

		pToolBar.add(btnSave, null);
		pToolBar.add(btnDelete, null);

		// pack();
	}

	void btnSelect_actionPerformed(ActionEvent e) {
		searchableControl.clear();
		if (!multiSelect && selectedItemsTable.getTable().getRowCount() > 0) {
			java.awt.Toolkit.getDefaultToolkit().beep();
			return;
		}

		try {
			int[] arr = allItemsTable.getTable().getSelectedRows();
			SLDataObject item;
			boolean found;

			for (int i = 0; i < arr.length; i++) // loop through selected accounts from "All Items"
			{
				item = (SLDataObject) allTm.itemAtTableRow(arr[i]);
				found = false;
				if (searchableComboBox == null || searchableComboBox.select_once) {
					for (int x = 0; x < selectedItemsTable.getTable().getRowCount(); x++)// check if item already exists in "Selected Items"
					{
						SLDataObject selectedItem = (SLDataObject) selectedTm.itemAtTableRow(x);
						if (selectedItem.listString().equals(item.listString())) {
							java.awt.Toolkit.getDefaultToolkit().beep();
							found = true;
							break;
						}
					}
				}
				if (!found)
					selectedTm.addDataRow(allTm.itemAtTableRow(arr[i]));
			}// end for
		}// end try
		catch (Exception ex) {
			JOptionPane.showMessageDialog(this, "Please select item");
			ex.printStackTrace();
		}
	}

	void btnClose_actionPerformed(ActionEvent e) {
		this.hide();
	}

	void btnClear_actionPerformed(ActionEvent e) {
		selectedTm.clear();
		searchableControl.clear();
		if (searchableComboBox != null)
			selectionCoB.setSelectedIndex(0);
	}

	void btnDeselect_actionPerformed(ActionEvent e) {
		selectedTm.deleteTableRows(selectedItemsTable.getTable().getSelectedRows());
	}

	void btnOk_actionPerformed(ActionEvent e) {
		if (searchableComboBox == null) {
			this.hide();
			return;
		}
		
		Enumeration en = selectedTm.getRowsVector().elements();
		StringBuffer sb = new StringBuffer();
		String holder;
		while (en.hasMoreElements()) {
			SLDataObjectAdaptor item = (SLDataObjectAdaptor) en.nextElement();
			if (searchableComboBox.getDisplayDescr())
				holder = item.getDescr();
			else
				holder = item.listString();

			if (holder != null && !holder.equals(SelectAll.SELECT_ALL) && !holder.equals("--  NONE  --")) {
				if (sb.length() > 0)
					sb.append(",");
				sb.append(holder);
			}
		}
		if (sb.length() < 1 && searchableComboBox.items.size() > 0)
			searchableComboBox.setSelectedIndex(0);
		else if (sb.length() > 0)
			searchableComboBox.setSelectedItem(sb);
				
	
		selectedTm.clear();
		this.hide();
	}

	void btnSave_actionPerformed(ActionEvent e) {
		if (allTm.getRowCount() < 1)
			return;
		if (selectionCoB.getSelectedIndex() != 0 && selectionCoB.getSelectedIndex() != -1) // user might want to update selection
		{
			int ret = JOptionPane.showConfirmDialog(pParent, "Overwrite selection '" + selectionCoB.getSelectedItem() + "'", selectionCoB.getSelectedItem().toString(), JOptionPane.YES_NO_OPTION);
			if (ret == JOptionPane.YES_OPTION)// update selection
			{
				String code = selectionCoB.getSelectedItem().toString();
				Class cl = getComboClass();
				if (cl == null) {
					JOptionPane.showMessageDialog(this, "This selection can not be updated");
					Util.debug("SearchableComboDialog: Can not update selection. Either Vector of SLDataObjects is empty or all objects are placeholders");
					return;
				}
				Vector v = selectedTm.getRowsVector();
				SearchableItem.updMostSearchedSelection(code, cl, v);
				return;
			}
		}
		saveNewSelection();
	}

	void saveNewSelection() {
		SearchableComboSelectionDialog selectionDialog = new SearchableComboSelectionDialog(this);
		SelectionReturnValue obj = selectionDialog.showDialog();

		if (obj == null)
			return;
		String inputValue = obj.tname;
		if (inputValue.equals(""))
			return;
		int shared = 0;
		if (obj.isShared)
			shared = 1;

		Class cl = getComboClass(); // Combination of user id, class of objects in the combo box, and selection name make a selection unique
		if (cl == null) {
			JOptionPane.showMessageDialog(this, "This selection can not be saved");
			Util.debug("SearchableComboDialog: Can not save new selection. Either Vector of SLDataObjects is empty or all objects are placeholders");
			return;
		}

		Vector v = selectedTm.getRowsVector();
		if (SearchableItem.insMostSearchedSelection(inputValue, cl, v, shared))
			selectionCoB.addItem(inputValue);
		else
			JOptionPane.showMessageDialog(this, "This name already exists"); // most likely unique index 'i_u_Primary'is violated
	}

	void selectionCoB_actionPerformed(ActionEvent e) {
		if (selectionCoB.getSelectedIndex() != 0 && selectionCoB.getSelectedIndex() != -1) {
			Class cl = getComboClass();
			if (cl != null)
				selectedTm.setTableData(SearchableItem.getMostSearchedSelectionItem(selectionCoB.getSelectedItem().toString(), cl));
		}
	}

	void btnDelete_actionPerformed(ActionEvent e) {
		if (selectionCoB.getSelectedIndex() != 0 && selectionCoB.getSelectedIndex() != -1) {
			int ret = JOptionPane.showConfirmDialog(pParent, "Delete selection '" + selectionCoB.getSelectedItem() + "'?", selectionCoB.getSelectedItem().toString(), JOptionPane.YES_NO_OPTION);
			if (ret == JOptionPane.YES_OPTION)// delete selection
			{
				String code = selectionCoB.getSelectedItem().toString();
				Class cl = getComboClass();
				if (cl == null) {
					JOptionPane.showMessageDialog(this, "This selection can not be updated");
					Util.debug("SearchableComboDialog: Can not update selection. Either Vector of SLDataObjects is empty or all objects are placeholders");
					return;
				}
				if (SearchableItem.delMostSearchedSelection(code, cl))
					selectionCoB.removeItem(code);
				return;
			}
		}
	}

	public void disableSaveFunctionality() {
		btnSave.setEnabled(false);
		btnDelete.setEnabled(false);
		super.selectionCoB.setEnabled(false);
	}
}
